import React, { Component } from 'react'
import { Route } from 'react-router-dom'
import { hasToken } from 'utils/storage'
import { Redirect } from 'react-router-dom'

// 封装根据token存在判断访问权限
export default class AuthRoute extends Component {
  render() {
    // rest剩余属性
    const { component: Component, ...rest } = this.props
    return (
      <Route
        {...rest}
        render={(props) => {
          // 有token就正常跳转，没有token就返回登录页
          if (hasToken()) {
            return <Component {...props} />
          } else {
            // this.props.history.push('/login')
            // return <Redirect to="/login"></Redirect>
            return (
              <Redirect
                to={{
                  pathname: '/login',
                  // 跳转到登录页面，把当前地址传过去，重新登录后还回到原来的页面
                  // search: '?from=' + props.location.pathname,
                  state: {
                    from: props.location.pathname,
                  },
                }}
              ></Redirect>
            )
          }
        }}
      ></Route>
    )
  }
}
